/**
 * rmrb客户端bridge.js
 * - 由于历史原因，原生调用web端方法的时候，需要全局对象：Base 、 article内的方法，所以开发者需要预留这两个全局变量 _(:з」∠)_
 */

;
(function (global) {

    var require;

    function _require(url, onload) {
        var doc = document;
        var head = doc.head || (doc.getElementsByTagName("head")[0] || doc.documentElement);
        var node = doc.createElement("script");
        node.onload = onload;
        node.onerror = function () {};
        node.async = true;
        node.src = url[0];
        head.appendChild(node);
    }

    // 对不支持Object.assign方法的环境进行兼容
    if (typeof Object.assign != 'function') {
        Object.assign = function (target) {
            'use strict';
            if (target == null) {
                throw new TypeError('Cannot convert undefined or null to object');
            }

            target = Object(target);
            for (var index = 1; index < arguments.length; index++) {
                var source = arguments[index];
                if (source != null) {
                    for (var key in source) {
                        if (Object.prototype.hasOwnProperty.call(source, key)) {
                            target[key] = source[key];
                        }
                    }
                }
            }
            return target;
        };
    }

    function sTrim(s) {
        return s.replace(/(^\s*)|(\s*$)/g, "");
    };

    function getAgentString(name) {
        var uaString = window.navigator.userAgent,
            mainString = uaString.slice(uaString.indexOf('?')),
            reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = mainString.substr(1).match(reg);
        if (r != null) {
            return unescape(r[2]);
        }
        return null;
    }

    function factory() {
        var Bridge = {
            // 基础方法、判断平台、是否在壳子内
            env: getAgentString('env'),
            isIOS: /iphone|ipad|ipod/.test(window.navigator.userAgent.toLowerCase()),
            isAndroid: /android/.test(window.navigator.userAgent.toLowerCase()),
            platform: function () {
                if (this.isIOS) {
                    return 'IOS';
                }
                if (this.isAndroid) {
                    return 'Android';
                }
            },
            isNative: typeof nativeBridge != "undefined",
            isNativeUA: navigator.userAgent.match(/DailyNewspaper/i) ? true : false,
            uaData: function () {
                if (!this.isNativeUA) return false;
                var uaString = navigator.userAgent,
                    mainString = uaString.slice(uaString.indexOf('DailyNewspaper'));

                mainString = mainString.slice(0, mainString.indexOf('?'));

                var version = mainString.match(/DailyNewspaper\/(\S*)\s?\(/)[1],
                    params = mainString.slice(mainString.indexOf('(') + 1, -1).split(';');
                if (this.isIOS) {
                    params[1] = params[1].replace('iOS ', '');
                }
                return {
                    version: version,
                    sys: sTrim(params[0]),
                    sysver: sTrim(params[1]),
                    model: sTrim(params[2])
                }
            },
            compareVer: function (v, type) {
                if (!this.isNativeUA) return false;
                if (v) {
                    var arr1 = !type ? this.uaData().version.split('.') : this.uaData().sysver.split('.');
                    var arr2 = v.split('.');

                    var minLength = Math.min(arr1.length, arr2.length),
                        position = 0,
                        diff = 0;

                    while (position < minLength && ((diff = parseInt(arr1[position]) - parseInt(arr2[position])) == 0)) {
                        position++;
                    }

                    diff = (diff != 0) ? diff : (arr1.length - arr2.length);

                    return diff >= 0;

                } else {
                    console.error('compareVer：请传入版本号字符串');
                }
            },
            // 历史原因：base、artcile 都是原生调取页面的方法合集，如果有需要，需要执行window.Base = Bridge.base; window.article = Bridge.article;
            base: {

            },
            article: {

            },
            /**
             * H5调用原生的核心方法 nativeBridge[method](data);
             * [method]         String      需要调用的方法名
             * [data]           Object      需要给原生的数据
             * [callback]       String      成功回调，callback必须是全局变量，否则原生无法调用
             * [erCallback]     String      失败回调，errCallback必须是全局变量， 否则原生无法调用
             */
            request: function (method, data, callback, errCallback) {
                if (!this.isNativeUA) return false;

                var params = {
                        methodName: callback || null,
                        errorMethodName: errCallback || null
                    },
                    _data = {};

                if (method == 'internalJump') { // fix ios和安卓接受的数据格式不同的问题
                    var sData = typeof data == 'string' ? JSON.parse(data) : data;

                    _data.data = this.isIOS ? JSON.stringify(sData) : sData;
                } else if (method.indexOf('Share') > 0) {
                    _data.shareData = data;
                } else {
                    _data = data;
                }
                params = Object.assign(params, _data);

                var jsonStr = JSON.stringify(params);
                try {
                    nativeBridge[method](jsonStr);
                } catch (e) {
                    console.error('调用 nativeBridge[method](jsonStr) 出错');
                    console.error('只有人民日报客户端内才有全局变量 nativeBridge');
                }

            }
        };

        return Bridge;
    }

    if (typeof define === "function" && (define.cmd || define.amd)) {
        if (define.cmd) {
            require = seajs.use;
        } else {
            if (define.amd) {
                require = window.require;
            }
        }
        define(function () {
            return factory();
        });
    } else {
        require = _require;
        window.Bridge = factory();
    }

})(typeof window !== 'undefined' ? window : global);